package io.renren.modules.business.service.impl;

import io.renren.common.config.ImageUploadConfig;
import io.renren.common.utils.FileUtils;
import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.UUID;

@Service
public class FileUploadServiceIml {
    @Autowired
    private ImageUploadConfig imageUploadConfig;


    /**
     * @param multipartFile
     * @return 返回图片地址
     */
    public R uploadFile(MultipartFile multipartFile) {
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("[-]", "");

        String filePath = uuid.substring(0, 2);
        String uploadPath = imageUploadConfig.getPath() + filePath;
        String returnUrl = imageUploadConfig.getHost() + filePath + "/" + uuid + ".jpg";
        String url = imageUploadConfig.getPath() + filePath + "/" + uuid + ".jpg";

        try {
            File fileDirPath = new File(uploadPath);
            if (!fileDirPath.exists()) {
                fileDirPath.mkdirs();
            }

            File file = new File(url);
            // 转存文件
            multipartFile.transferTo(file);

            FileUtils.commpressPicCycle(url, 0.9);
        } catch (Exception e) {
            return R.error(2, "创建文件失败");
        }
        return R.ok().put("data", returnUrl);
    }


}
